<template>
	<view class="">
		<view class="">
			<swiper class="swiper" circular autoplay :interval="5000" :duration="300" indicator-active-color="#ffffff"
				indicator-color="rgba(255,255,255,0.5)" indicator-dots @change="bannerChange">
				<swiper-item v-for="(item, index) in list" :key="index" @click="clickBanner(item,index)">
					<view class="swiper">
						<image v-if="getItemType(item) === 'image'" style="width: 100%;height: 100%;"
							:src="getSource(item)" mode="aspectFill">
						</image>
						<video v-if="getItemType(item) === 'video'" :enable-progress-gesture="false"
							style="width: 100%;height: 100%;" :id="`video-${index}`" :src="getSource(item)"></video>
					</view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			list: {
				typeof: Array,
				default: () => []
			},
			keyName: {
				typeof: String,
				default: () => 'url'
			},
		},
		components: {},
		data() {
			return {
				currentIndex: 0
			}
		},
		onLoad() {

		},
		onShow() {

		},
		methods: {
			getItemType(item) {
				if (typeof item === 'string') return uni.$u.test.video(this.getSource(item)) ? 'video' : 'image'
				if (typeof item === 'object' && this.keyName) {
					if (!item.type) return uni.$u.test.video(this.getSource(item)) ? 'video' : 'image'
					if (item.type === 'image') return 'image'
					if (item.type === 'video') return 'video'
					return 'image'
				}
			},
			getSource(item) {
				if (typeof item === 'string') return item
				if (typeof item === 'object' && this.keyName) return item[this.keyName]
				else uni.$u.error('请按格式传递列表参数')
				return ''
			},
			clickBanner(item, index) { //点击
				this.$emit('clickBanner', {
					item: item,
					index: index
				})
			},
			bannerChange(e) {
				// 当前的激活索引
				const {
					current
				} = e.detail
				this.pauseVideo(this.currentIndex)
				this.currentIndex = current
				this.$emit('change', current)
			},
			// 切换轮播时，暂停视频播放
			pauseVideo(index) {
				const lastItem = this.getSource(this.list[index])
				if (uni.$u.test.video(lastItem)) {
					// 当视频隐藏时，暂停播放
					const video = uni.createVideoContext(`video-${index}`, this)
					video.pause()
				}
			},
		},
		computed: {

		},
		watch: {

		}
	}
</script>

<style lang="scss">
	.swiper {
		width: 100%;
		height: 306rpx;
		border-radius: 0;
		overflow: hidden;
	}
</style>